package com.dominator.socket;


import com.dominator.enums.ReqEnums;
import com.dominator.utils.exception.ApiException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 *springbean获取工具
 * @author dl
 */
@Slf4j
public class BeanLoader {


    private static ApplicationContext applicationContext;

    static {
        try {
            initApplicationContext();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 初始化ApplicationContext对象
     *
     * @throws Exception
     */
    private static void initApplicationContext() throws Exception {
        applicationContext = ApplicationContextRegister.getApplicationContext();
    }

    /**
     * 返回ApplicationContext对象
     *
     * @return ApplicationContext 返回的ApplicationContext实例
     */
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    /**
     * 获取一个SpringBean服务
     *
     * @param pBeanId
     *            Spring配置文件名中配置的SpringID号
     * @return Object 返回的SpringBean实例
     */
    public static Object getSpringBean(String pBeanId) {
        Object springBean = null;
        try {
            springBean = applicationContext.getBean(pBeanId);
        } catch (NoSuchBeanDefinitionException e) {
            String msg = "Spring容器中没有找到ID为:[" + pBeanId + "]的SpringBean组件,请检查!";
            throw new ApiException(ReqEnums.SYS_ERROR.getCode(),msg );
        }
        return springBean;
    }

}
